package com.bowen.spike.task;


import com.bowen.spike.constants.SystemConstants;
import com.bowen.spike.entity.Voucher;
import com.bowen.spike.my_enum.VoucherStatus;
import com.bowen.spike.service.IVoucherService;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;


/**
 * 定时清理过期优惠劵
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class DealWithExpiredVouchersTask {

    private final RedisTemplate<String, String> redisTemplate;
    private final IVoucherService voucherService;
    private static final DefaultRedisScript<Long> VOUCHER_SCRIPT;

    static {
        VOUCHER_SCRIPT = new DefaultRedisScript<>();
        VOUCHER_SCRIPT.setLocation(new ClassPathResource("scanAndExpireVouchers.lua"));
        VOUCHER_SCRIPT.setResultType(Long.class);
    }

    /**
     * 定时任务
     */
    @Scheduled(cron = "*/59 * * * * *")
    public void processExpiredVouchers() {
        // 获取并删除过期的优惠券ID，一次最多获取1000个
        List<String> expiredVoucherIds = redisTemplate.opsForSet().pop(SystemConstants.VOUCHER_EXPIRED, 1000);

        if (expiredVoucherIds == null || expiredVoucherIds.isEmpty()) {
            log.info("没有过期的优惠券需要处理");
            return;
        }

        // 批处理过期的优惠券
        List<Voucher> list = expiredVoucherIds.stream()
                .map(a -> new Voucher().setId(Long.parseLong(a)).setStatus(VoucherStatus.OVERDUE))
                .toList();

        voucherService
                .updateBatchById(list);

        log.info("过期优惠券处理完成，共处理 {} 个优惠券", expiredVoucherIds.size());
    }

    /**
     * 定时任务2
     */
    @Scheduled(cron = "*/59 * * * * *")
    public void processExpiredVouchers2() {

        try {
            redisTemplate.execute(VOUCHER_SCRIPT, Collections.emptyList());
        } catch (Exception e) {
            log.info("扫描异常:{}", e.toString());
        }

        log.info("扫描过期优惠券完成");
    }
}


